package com.marcocirillo.justweet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import twitter4j.*;

public class JusTweet {

	/**
	 * @param args
	 */
	
	private String username;
	//private String password;
	private Twitter user;
	
	public JusTweet(String username, String password)
	{
		this.username = username;
		this.user = (Twitter) new TwitterFactory().getInstance(username, password);
	}
	
	public Status updateStatus(String status) throws TwitterException
	{
		Status returnStatus = this.user.updateStatus(status);
		return returnStatus;
		
	}
	
	public Status getCurrentStatus() throws TwitterException
	{
		return getCurrentUser().getStatus();
	}
	
	public User getCurrentUser() throws TwitterException
	{
		return this.user.showUser(this.username);
	}
	
	public String toString()
	{
		String s = null;
		
		try
		{
			s = this.user.getScreenName() +"'s Status is now: " + getCurrentStatus().getText();
		} catch (TwitterException e)
		{
			s = e.getMessage();
		}
		
		return s;
	}
	
	public boolean isAuthenticated()
	{
		boolean isVerified = false;
		try
		{
			this.user.verifyCredentials();
			isVerified = true;
		} catch (TwitterException e)
		{
			System.out.println("Invalid Username/Password");
		}
		return isVerified;
	}
	
	public String getStringURL() throws TwitterException
	{
		return getCurrentUser().getURL().toString();
	}
	
	public static void saveAccount(String username, String password)
	{
		File settings = new File("JusTweet.ini");
		if (!settings.exists())
		{
			try {
				System.out.println("Creating settings file");
				settings.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("File Writable: " + settings.canWrite());
		System.out.println("File is File: " + settings.isFile());
		try {
			System.out.println("trying to write...");

		    FileWriter fstream = new FileWriter(settings, false);
			PrintWriter pw = new PrintWriter(fstream);
	        pw.println(username);
	        pw.println(password);
	        pw.close();
	        System.out.println("write complete");
		} catch (IOException e)
		{
			System.out.println("Write Failed");
			e.printStackTrace();
		}

	}

}
